package org.lanyu.springainovel.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lanyu.springainovel.common.vo.RestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义访问拒绝处理器
 * 当用户尝试访问受保护资源但没有足够权限时，返回统一的RestVO格式响应
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置响应状态码和内容类�?        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        
        // 创建统一的RestVO格式响应
        RestVO<?> restResponse = RestVO.fail(401, "访问被拒绝，请重新登录: " + accessDeniedException.getMessage());
        
        // 将响应写入输出流
        String jsonResponse = objectMapper.writeValueAsString(restResponse);
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
}
